package utility.text.mask;
import java.awt.event.FocusAdapter;   
import java.awt.event.FocusEvent;   
import javax.swing.JFormattedTextField;   
import javax.swing.JTextField;   
import javax.swing.event.CaretEvent;   
import javax.swing.event.CaretListener;   
import javax.swing.text.AttributeSet;   
import javax.swing.text.BadLocationException;   
import javax.swing.text.PlainDocument;   
import javax.swing.text.SimpleAttributeSet;   

/**  
 * Component JMoneyField  
 * @author Dyorgio da Silva Nascimento e Modificado por Denilson Dias 
 */   
public class JTextDecimal extends JFormattedTextField {   

	private static final long serialVersionUID = -5712106034509737967L;   
	private static final SimpleAttributeSet nullAttribute = new SimpleAttributeSet();  
	private int decimal = 0;
	private String modelo = null;

	/**  
	 * Creates a new instance of JMoneyField  
	 */   
	public JTextDecimal(int casasDecimais) {   
		this.setHorizontalAlignment( JTextField.RIGHT );   
		this.setDocument(new MoneyFieldDocument());   
		this.addFocusListener(new MoneyFieldFocusListener());   

		modelo = "0,";
		decimal = casasDecimais;
		for (int i = 0; i<decimal;i++)
			modelo = modelo + "0";
		this.setText(modelo);

		this.addCaretListener(new CaretListener(){   
			public void caretUpdate(CaretEvent e) {   
				if (e.getDot() != getText().length() ) {   
					getCaret().setDot(getText().length());   
				}   
			}   
		});   
	}   

	private final class MoneyFieldFocusListener extends FocusAdapter{   
		public void focusGained(FocusEvent e) {   
			selectAll();   
		}   
	}   

	private final class MoneyFieldDocument extends PlainDocument {   

		/**  
		 *  
		 */   
		private static final long serialVersionUID = -3802846632709128803L; 

		private String formatValue(String value,int offs)
		{
			if (value!="")
			{	
				int pos = 0; 
				for (int i = 0;i < value.length() ;i++)
					if (value.substring(i,i+1).equals(".")  || value.substring(i,i+1).equals(","))
						pos = i;

				if (offs != -1)
					if(pos > 0)					
						for (int i = value.length() - pos - 1;i<decimal;i++)
							value = value + "0";	
			}
			return value;
		}

		public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {   
			String original = getText(0,getLength());   

			str = formatValue(str,offs); 
			// Permite apenas digitar ate 16 caracteres (9.999.999.999,99)
			if (original.length()<16) {   
				StringBuffer mascarado = new StringBuffer();   
				if (a != nullAttribute) {   
					//limpa o campo   
					remove(-1,getLength());   

					mascarado.append((original+str).replaceAll("[^0-9]",""));   
					for (int i = 0; i < mascarado.length(); i++){   
						if (!Character.isDigit(mascarado.charAt(i))){   
							mascarado.deleteCharAt(i);   
						}   
					}   
					Long number = new Long(mascarado.toString());   

					mascarado.replace(0, mascarado.length(), number.toString());   

					if ( mascarado.length() < decimal+1 )   
					{   
						if ( mascarado.length() < decimal ) {                                
							for(int i = mascarado.length();i < decimal;i++)
								mascarado.insert(0,"0");
							mascarado.insert(0,",");   
							mascarado.insert(0,"0");   
						}else if ( mascarado.length() == decimal ) { 
							mascarado.insert(0,",");   
							mascarado.insert(0,"0");   
						}   
					}else{   
						mascarado.insert(mascarado.length()-(decimal),",");   
					}   

					if ( mascarado.length() > decimal + 4 ) {   
						mascarado.insert(mascarado.length()- (decimal + 4), '.');   
						if (mascarado.length() > decimal+8 ) {   
							mascarado.insert(mascarado.length()-(decimal + 8), '.');   
							if (mascarado.length() > decimal+12 ) {   
								mascarado.insert(mascarado.length()-(decimal + 12 ), '.');   
							}   
						}   
					}   
					super.insertString(0, mascarado.toString(), a);   
				}else{   
					if (original.length() == 0){   
						super.insertString(0, modelo, a);   
					}   
				}   
			}   
		}   

		@Override   
		public void remove(int offs, int len) throws BadLocationException {   
			if ( len == getLength() ) {   
				super.remove(0, len);   
				if (offs != -1){   
					insertString(0, "",nullAttribute);   
				}   
			}else{   
				String original = getText(0, getLength()).substring(0, offs) + getText(0, getLength()).substring(offs+len);   
				super.remove(0, getLength());   
				insertString(-1,original,null);   
			}   
		}   
	}   
} 